import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_give/pages/auth/login_page.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:rapid_kit/rapid_kit.dart';
import '../../common_ui/dialog/dialog_factory.dart';
import '../../common_ui/loading.dart';
import '../../route/route_utils.dart';
import '../../route/routes.dart';
import '../../sample/configure/constants.dart';
import '../../utils/LogUtils.dart';
import '../../utils/constants.dart';
import '../../utils/persistent_storage.dart';
import '../../utils/sp_utils.dart';
import '../personal/personal_page.dart';
import '../personal/personal_vm.dart';

/// 设置页面
class SettingPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _SettingkeyPage();
  }
}

Future<bool> _onWillPop() async {
  PersonalPageState.globalKeythere.currentState?.reloadData();
  return true; // 返回true表示允许返回，返回false表示阻止返回
}

class _SettingkeyPage extends State<SettingPage> {
  PersonViewModel viewModel = PersonViewModel();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff),
      statusBarIconBrightness: Brightness.dark,
    ));
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        backgroundColor: Color(0xFFfafafa),
        appBar: _buildTitleBar(context),
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(16.0), // 设置内边距
            child: Column(
              // crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  alignment: Alignment.centerLeft, // 左对齐
                  child: Text(
                    "账户安全",
                    style: TextStyle(color: Color(0xFFb2b2b2)),
                    textAlign: TextAlign.left, // 文字左对齐
                  ),
                ),
                SizedBox(height: 20),
                _buildsafetyRow(),
                SizedBox(height: 20),
                Container(
                  alignment: Alignment.centerLeft, // 左对齐
                  child: Text(
                    "其他设置",
                    style: TextStyle(color: Color(0xFFb2b2b2)),
                    textAlign: TextAlign.left, // 文字左对齐
                  ),
                ),
                SizedBox(height: 20),
                _buildrestRow(),
                Spacer(),
                _buildLogoutButton(),
                SizedBox(height: 40),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _openAppSettings() async {
    try {
      await MethodChannel('com.example.witvideo_app/settings')
          .invokeMethod('openAppSettings');
    } catch (e) {
      print('错误: $e');
      // 提示用户手动打开设置
      throw '无法自动打开设置页面，请手动前往设置。';
    }
  }

  AppBar _buildTitleBar(BuildContext context) {
    return AppBar(
      toolbarHeight: 60,
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios), // 使用没有横线的返回箭头图标
        onPressed: () {
          _onWillPop();
          // 返回操作
          Navigator.of(context).pop();
        },
      ),
      backgroundColor: Color(0xFFffffff),
      automaticallyImplyLeading: false,
      // 禁用自动生成的返回按钮
      title: Text(
        "设置",
        style: TextStyle(
          fontSize: 17,
          fontFamily: "PingFang SC",
          fontWeight: FontWeight.w600,
        ),
      ),
      centerTitle: true,
    );
  }

  // 退出登录
  Widget _buildLogoutButton() {
    return SizedBox(
      width: 270, // 设置按钮宽度为400
      height: 45, // 设置按钮高度为40
      child: ElevatedButton(
        onPressed: () {
          DialogFactory.instance.showNeedLogoutDialog(
            context: context,
            dismissClick: () {
              //是否显示更新红点
              // viewModel.shouldShowUpdateDot();
            },
            confirmClick: () async {
              Loading.showLoading();
              LogUtils.w("============退出登录========");
              try {
                await SpUtils.saveString(Constants.SP_TG_TOKEN, "");
                await SpUtils.saveString(Constants.SP_ZHSL_TOKEN, "");
                await SpUtils.saveString(Constants.SP_USER_ID, "");
                await SpUtils.saveString(Constants.BUT_EQLIST_PRICE, "0");
                // 不能返回 - 没有清空应用数据
                await SharedPreferencesUtil.instance
                    .setString(SampleConstants.storageKeyLoginToken, "");
                await AccountService.logout();
              } catch (e) {
                LogUtils.e("退出登录失败: $e");
                Loading.dismissAll();
                RouteUtils.pushAndRemoveUntil(context, LoginPage());
              } finally {
                Loading.dismissAll();
                RouteUtils.pushAndRemoveUntil(context, LoginPage());
              }
            },
          );
        },
        style: ElevatedButton.styleFrom(
          backgroundColor: Color(0xFFececec),
          foregroundColor: Color(0xFFececec),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 80),
          // 调整水平内边距
          elevation: 0,
          shadowColor: Colors.transparent,
        ),
        child: const Text(
          '退出登录',
          style: TextStyle(fontSize: 16, color: Color(0xFFfc3d49)),
          textAlign: TextAlign.center, // 确保文字居中
        ),
      ),
    );
  }

  // 账户安全
  Widget _buildsafetyRow() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
        boxShadow: [
          BoxShadow(
            color: Color(0xFFf8f7f7), // 设置阴影颜色
            offset: Offset(0, 2), // 设置阴影偏移量
            blurRadius: 4.0, // 设置阴影模糊半径
            spreadRadius: 0.0, // 设置阴影扩散半径
          ),
        ],
      ),
      padding: EdgeInsets.only(
        top: 7, // 上边距
        bottom: 7, // 下边距
        left: 5, // 左边距
        right: 0, // 右边距
      ),
      child: Column(
        children: [
          InkWell(
            onTap: () {
              RouteUtils.pushForNamed(context, RoutePath.savepasswordPage);
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '修改密码',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {
              RouteUtils.pushForNamed(context, RoutePath.unsubscribePage);
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '注销账号',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 其他
  Widget _buildrestRow() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
      ),
      padding: EdgeInsets.only(
        top: 7, // 上边距
        bottom: 7, // 下边距
        left: 5, // 左边距
        right: 0, // 右边距
      ),
      child: Column(
        children: [
          InkWell(
            onTap: () {
              // _openAppSettings();
              openAppSettings();
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '消息通知设置',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {
              DialogFactory.instance.showNeedUsedataDialog(
                context: context,
                dismissClick: () {
                  //是否显示更新红点
                  // viewModel.shouldShowUpdateDot();
                },
                confirmClick: () async {
                  viewModel.logout((value) async {
                    if (value) {
                      // 清除应用数据
                      await SystemNavigator.pop();
                    }
                  });
                  // RouteUtils.pushForNamed(context, RoutePath.loginPage);
                },
              );
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '清除应用数据',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {
              RouteUtils.pushForNamed(context, RoutePath.AgreementPage);
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '用户协议',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {
              RouteUtils.pushForNamed(context, RoutePath.privacyPage);
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '隐私政策',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
          InkWell(
            onTap: () {
              RouteUtils.pushForNamed(context, RoutePath.regardsPage);
            },
            child: Container(
              padding: EdgeInsets.all(13.0), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '关于我们',
                    style: TextStyle(fontSize: 16),
                  ),
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Color(0xFF5a5a5a)),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
